<?php

namespace App\Hospital\Controllers;

use App\Admin\Repositories\HospitalAdministrator;
use App\Exceptions\Arr;
use App\Models\Hospital;
use App\Models\HospitalAdminUserHospital;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Auth\Permission;
use App\Models\HospitalAdministrator as AdministratorModel;
use Dcat\Admin\Show;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Tree;
use Dcat\Admin\Http\Controllers\AdminController;

class HospitalUserController extends AdminController
{

    protected $translation = 'hospital-user';

    protected function grid()
    {
        return Grid::make(HospitalAdministrator::with(['roles']), function (Grid $grid) {
            $grid->model()
                ->select(['hospital_admin_users.*'])
                ->join('hospital_admin_users_hospital','hospital_admin_users_hospital.hospital_admin_users_id','=','hospital_admin_users.id')
                ->where('hospital_admin_users_hospital.hospital_id',Admin::user()->hospital_id);
            $grid->column('id', 'ID')->sortable();
            $grid->column('username');
            $grid->column('name');

            if (config('hospital.permission.enable')) {
                $grid->column('roles')->pluck('name')->label('primary', 3);

                $permissionModel = config('hospital.database.permissions_model');
                $roleModel = config('hospital.database.roles_model');
                $nodes = (new $permissionModel())->allNodes();
                $grid->column('permissions')
                    ->if(function () {
                        return ! $this->roles->isEmpty();
                    })
                    ->showTreeInDialog(function (Grid\Displayers\DialogTree $tree) use (&$nodes, $roleModel) {
                        $tree->nodes($nodes);

                        foreach (array_column($this->roles->toArray(), 'slug') as $slug) {
                            if ($roleModel::isAdministrator($slug)) {
                                $tree->checkAll();
                            }
                        }
                    })
                    ->else()
                    ->display('');
            }

            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->quickSearch(['id', 'name', 'username']);

            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->showColumnSelector();
            $grid->disableEditButton();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->getKey() == AdministratorModel::DEFAULT_ID) {
                    $actions->disableDelete();
                }
            });
        });
    }

    protected function detail($id)
    {
        return Show::make($id, HospitalAdministrator::with(['roles']), function (Show $show) {
            $show->field('id');
            $show->field('username');
            $show->field('name');



            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function form()
    {
        return Form::make(HospitalAdministrator::with(['roles','hospitals']), function (Form $form) {
            $userTable = config('hospital.database.users_table');

            $connection = config('hospital.database.connection');

            $id = $form->getKey();

            $form->display('id', 'ID');

            $form->text('username', "手机号")
                ->required()
                ->creationRules(['required', "unique:{$connection}.{$userTable}",'regex:/^1[23456789]\d{9}$/'], [
                    'regex' => '手机号码格式错误',
                ])
                ->updateRules(

                    ['required', "unique:{$connection}.{$userTable},username,$id",'regex:/^1[23456789]\d{9}$/'],

                    [
                        'regex' => '手机号码格式错误',
                    ]
                );
            $form->text('name', '姓名')->required();


            $rolesIds = [];
            $roles = $form->model()->roles;
            if($roles) {
                $rolesIds = Arr::pluck($roles->toArray(), 'id');
            }
            if (config('hospital.permission.enable') && !in_array(1,$rolesIds)) {
                $form->multipleSelect('roles', trans('hospital.roles'))
                    ->options(function () {
                        $roleModel = config('hospital.database.roles_model');

                        return $roleModel::all()->where('id',"!=",1)->pluck('name', 'id');
                    })
                    ->customFormat(function ($v) {
                        return array_column($v, 'id');
                    });
            }
            $form->hidden('hospital_id')->value(Admin::user()->hospital_id);

            $form->display('created_at', trans('hospital.created_at'));
            $form->display('updated_at', trans('hospital.updated_at'));

            if ($id == AdministratorModel::DEFAULT_ID) {
                $form->disableDeleteButton();
            }
        })->saved(function (Form $form, $result) {
            $newId = $result;
            $hauh = HospitalAdminUserHospital::query()
                ->where('hospital_admin_users_id',$newId)
                ->where('hospital_id',$form->hospital_id)
                ->first();
            if(!$hauh){
                $hauh = new HospitalAdminUserHospital();
                $hauh->hospital_admin_users_id = $newId;
                $hauh->hospital_id = $form->hospital_id;
                $hauh->save();
            }
        });
    }

    public function destroy($id)
    {
        if (in_array(AdministratorModel::DEFAULT_ID, Helper::array($id))) {
            Permission::error();
        }

        return parent::destroy($id);
    }
}
